package com.lz.helper.idcard

import android.content.Context
import android.util.Log
import java.util.concurrent.atomic.AtomicBoolean

abstract class IDCardRequest(
    protected val context: Context,
    protected val readFinger: Boolean,
    protected val handler: IDCardHandler
) : Runnable {

    companion object {

        const val TAG = "IDCardRequest"

        //识别成功延时
        const val DELAYED_SUCCESS = 2000L

        //异常时的延时
        const val DELAYED_ERR = 1000L

        //初始化异常
        const val ERR_INIT = 1

        //打开异常
        const val ERR_OPEN = 2
    }

    //是否暂停, 暂停时将线程挂起
    private var isPaused = false

    //是否退出
    private var quit = AtomicBoolean(false)

    //线程wait notify
    private var async = Object()

    //暂停
    fun pause() {
        synchronized(async) { isPaused = true }
    }

    //恢复
    fun restart() {
        synchronized(async) { isPaused = false; async.notify() }
    }

    //中断退出
    fun quit() {
        synchronized(async) { quit.set(true); async.notify() }
    }

    //是否退出
    fun isQuit(): Boolean = quit.get()

    //等待处理
    protected fun await() {
        synchronized(async) {
            while (isPaused && !quit.get()) {
                try {
                    Log.d(TAG, "...... IDCardOperator wait ......")
                    async.wait()
                    Log.d(TAG, "...... IDCardOperator resume  ......")
                } catch (_: InterruptedException) {
                }
            }
        }
    }

    //延时处理
    protected fun delay(time: Long) {
        synchronized(async) {
            if (!isPaused) {
                try {
                    async.wait(time)
                } catch (_: InterruptedException) {
                }
            }
        }
    }

    //线程数据处理
    interface IDCardHandler {

        fun sendCardResult(idCard: IDCardInfo)

        fun sendCardError(code: Int)
    }

    interface Factory {

        fun create(context: Context, readFinger: Boolean, handler: IDCardHandler): IDCardRequest
    }
}